package com.xmpp.client;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;

import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.packet.DiscoverItems;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.xmpp.client.util.XmppTool;

/**
 * 登陆页面
 * @author chunjiang.shieh
 *
 */
public class FormLogin extends Activity implements OnClickListener {

	private static final String XMPP_RESOURCES = "Android";
	private EditText useridText, pwdText;
	private LinearLayout layout1, layout2;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.formlogin);

		this.useridText = (EditText) findViewById(R.id.formlogin_userid);
		this.pwdText = (EditText) findViewById(R.id.formlogin_pwd);

		this.layout1 = (LinearLayout) findViewById(R.id.formlogin_layout1);
		this.layout2 = (LinearLayout) findViewById(R.id.formlogin_layout2);

		Button btsave = (Button) findViewById(R.id.formlogin_btsubmit);
		btsave.setOnClickListener(this);
		Button btcancel = (Button) findViewById(R.id.formlogin_btcancel);
		btcancel.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.formlogin_btsubmit:
			final String USERID = this.useridText.getText().toString();
			final String PWD = this.pwdText.getText().toString();
			new Thread(new Runnable() {				
				@Override
				public void run() {
					handler.sendEmptyMessage(1);
					try {
						XmppTool.getConnection().login(USERID, PWD,XMPP_RESOURCES);
						Log.i("XMPPClient", "Logged in as " + XmppTool.getConnection().getUser());
						// status
						Presence presence = new Presence(Presence.Type.available);
						XmppTool.getConnection().sendPacket(presence);
						/*Intent intent = new Intent(FormLogin.this, FormClient.class);
						intent.putExtra("USERID", USERID);
						startActivity(intent);
						FormLogin.this.finish();*/
						
						
						//登陆成功
						join();
						
						
					} catch (XMPPException e) {
						XmppTool.closeConnection();
						handler.sendEmptyMessage(2);
					}					
				}
			}).start();
			break;
		case R.id.formlogin_btcancel:
			finish();
			break;
		}
	}
	
	
	
	
	
	
	private void join(){
		
		
		ArrayList<DiscoverItems.Item> listDiscoverItems = new ArrayList<DiscoverItems.Item>();  
	        // 获得与XMPPConnection相关的ServiceDiscoveryManager  
	        ServiceDiscoveryManager discoManager = ServiceDiscoveryManager  
	                .getInstanceFor(XmppTool.getConnection());  
	  
	        // 获得指定XMPP实体的项目  
	        // 这个例子获得与在线目录服务相关的项目  
	        DiscoverItems discoItems;  
	        try {  
	            discoItems = discoManager.discoverItems("conference.192.168.3.73");  
	            // 获得被查询的XMPP实体的要查看的项目  
	            Iterator it = discoItems.getItems();  
	            // 显示远端XMPP实体的项目  
	            while (it.hasNext()) {  
	                DiscoverItems.Item item = (DiscoverItems.Item) it.next();  
	                System.out.println(item.getEntityID());  
	                System.out.println(item.getName());  
	                listDiscoverItems.add(item);  
	            }  
	        } catch (XMPPException e) {  
	            e.printStackTrace();  
	        }  
		
	        
	        String multiUserRoom = listDiscoverItems.get(0).getName()+"@conference."+XmppTool.getConnection().getServiceName();//listDiscoverItems.get(0).getEntityID();
		    try {
		        MultiUserChat muc = new MultiUserChat(XmppTool.getConnection(), multiUserRoom);
		        // 创建聊天室,进入房间后的nickname
		        muc.join("Hello World");
		        ChatPacketListener chatListener = new ChatPacketListener(muc);
			    muc.addMessageListener(chatListener);
		    } catch (XMPPException e) {
		        // TODO Auto-generated catch block
		        e.printStackTrace();
		    }
	        
	        
	}
	
	
	
	
	
	
	
	
	class ChatPacketListener implements PacketListener{

		  private String _number;
		  private Date _lastDate;
		  private MultiUserChat _muc;
		  private String _roomName;

		  public ChatPacketListener(MultiUserChat muc) {
		   _number = "0";
		   _lastDate = new Date(0);
		   _muc = muc;
		   _roomName = muc.getRoom();
		  }

		  @Override
		  public void processPacket(Packet packet) {
		   System.out.println("消息格式:" + packet.toXML());
		  }
		  
		  
	}
	
	
	
	
	
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case 1:
				layout1.setVisibility(View.VISIBLE);
				layout2.setVisibility(View.GONE);
				break;
			case 2:
				layout1.setVisibility(View.GONE);
				layout2.setVisibility(View.VISIBLE);
				Toast.makeText(FormLogin.this, "login failure", Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
		};
	};
}